package com.fanshuai.algorithms.twopointer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 两数之和
 */
public class TwoSum {
    /**
     * 在一个无序的数组a中，求两数之和等于target的索引，没有返回{-1,-1}
     * 此问题暴力求解复杂度为o(N^2)，可以初始化一个hashmap，复杂度为o(N)
     * @param a
     * @param target
     * @return
     */
    public static int[] twoSum(int[] a, int target) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            List<Integer> indexs = map.get(a[i]);
            if (null == indexs) {
                indexs = new ArrayList<>();
            }
            indexs.add(i);
            map.put(a[i], indexs);
        }

        for (int i = 0; i < a.length; i++) {
            int other = target - a[i];
            if (map.containsKey(other)) {
                List<Integer> keyIndex = map.get(a[i]);
                if (other == a[i]) {
                    if (keyIndex.size() < 2) {
                        return new int[] {-1, -1};
                    } else {
                        return new int[] {keyIndex.get(0), keyIndex.get(1)};
                    }
                } else {
                    List<Integer> otherIndex = map.get(other);
                    return new int[] {keyIndex.get(0), otherIndex.get(0)};
                }
            }
        }
        return new int[] {-1, -1};
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 4, 5, 5, 7, 8, 8, 9, 1};

        int[] pos = twoSum(a, 10);
        System.out.println(pos[0] + ", " + pos[1]);

        pos = twoSum(a, 11);
        System.out.println(pos[0] + ", " + pos[1]);

        pos = twoSum(a, 12);
        System.out.println(pos[0] + ", " + pos[1]);

        pos = twoSum(a, 8);
        System.out.println(pos[0] + ", " + pos[1]);
    }
}
